package demo.rabbitmq;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 这里配置死信交换机和死信队列
 * 交换机
 * 队列
 * binding
 */
@Configuration
public class ExchangeAndQueueConfig {
    //死信交换机及队列
    public static final String DEATH_EXCHANGE ="death.exchange";
    public static final String DEATH_RECORD_CHECK_QUEUE ="call.record.check.death.queue";
    //死信和业务队里使用相同routing key
    public static final String RECORD_CHECK_KEY ="record.check";

    //业务交换机及其队列
    public static final String RECORD_EXCHANGE ="call.record.exchange";
    public static final String RECORD_CHECK_QUEUE ="call.record.check.queue";

    // 声明死信Exchange
    @Bean
    public DirectExchange deathExchange(){
        return new DirectExchange(DEATH_EXCHANGE,true,true);
    }
    // 声明死信 录音检查队列
    @Bean
    public Queue callRecordCheckDeathQueue(){
        return new Queue(DEATH_RECORD_CHECK_QUEUE,true,false,true);
    }
    // 绑定死信交换机和死信队列
    @Bean
    public Binding deathCallRecordBinding(@Qualifier("callRecordCheckDeathQueue") Queue queue,
                                 @Qualifier("deathExchange") DirectExchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(RECORD_CHECK_KEY);
    }

    // 声明业务Exchange
    @Bean
    public DirectExchange recordExchange(){
        return new DirectExchange(RECORD_EXCHANGE,true,true);
    }
    // 声明业务 录音检查队列
    @Bean
    public Queue callRecordCheckQueue(){
        Map<String, Object> args = new HashMap<>(3);
        //       x-dead-letter-exchange    声明  死信交换机
        args.put("x-dead-letter-exchange", DEATH_EXCHANGE);
//       x-dead-letter-routing-key    声明 死信路由键
        args.put("x-dead-letter-routing-key", RECORD_CHECK_KEY);
        // x-message-ttl  声明队列的TTL
        args.put("x-message-ttl", 6000);
        return QueueBuilder.durable(RECORD_CHECK_QUEUE).autoDelete().withArguments(args).build();
    }
    // 绑定死信交换机和死信队列
    @Bean
    public Binding delayBindingA(@Qualifier("callRecordCheckQueue") Queue queue,
                                 @Qualifier("recordExchange") DirectExchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(RECORD_CHECK_KEY);
    }
}
